package leetcode.每日一题;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：zsy
 * @date ：Created 2021/6/19 14:50
 * @description：https://leetcode-cn.com/problems/generate-parentheses/
 */
public class 括号生成 {

    @Test
    public void Test() {
        Solution solution = new Solution();
        List<String> list = solution.generateParenthesis(4);
        System.out.println(list.toString());
    }

    //剪枝
    /*class Solution {
        List<String> list = new ArrayList<>();
        int n;
        public List<String> generateParenthesis(int n) {
            this.n = n;
            backtrack(new StringBuilder(), 0, 0);
            return list;
        }

        private void backtrack(StringBuilder builder, int open, int close) {
            if (builder.length() == n * 2) {
                list.add(builder.toString());
                return;
            }
            //拿(
            if (open < n) {
                builder.append("(");
                backtrack(builder, open + 1, close);
                builder.deleteCharAt(builder.length() - 1);
            }
            //拿)
            if (open > close) {
                builder.append(")");
                backtrack(builder, open, close + 1);
                builder.deleteCharAt(builder.length() - 1);
            }
        }
    }*/


    class Solution {
        List<String> list = new ArrayList<>();
        int n;
        public List<String> generateParenthesis(int n) {
            //维护一个balance
            //每增加一个( balance + 1
            //每增加一个) balance - 1
            // balance的值始终不能为负数,balance的值不能超过n
            this.n = n;
            dfs(0, new StringBuilder());
            return list;
        }

        private void dfs(int balance, StringBuilder builder) {
            if (builder.length() == n * 2) {
                if (balance == 0)
                    list.add(builder.toString());
                return;
            }
            //拿(
            if (balance < n) {
                builder.append("(");
                dfs(balance + 1, builder);
                builder.deleteCharAt(builder.length() - 1);
            }
            //拿)
            if (balance > 0) {
                builder.append(")");
                dfs(balance - 1, builder);
                builder.deleteCharAt(builder.length() - 1);
            }
        }
    }
}


















